import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/HomeView.vue";
import Cart from "@/views/CartView.vue";
import BookDetail from "@/views/BookDetail.vue";
import Login from "@/views/LoginView.vue";
import Register from "@/views/RegisterView.vue";
import Orders from "@/views/OrdersView.vue";
import Favorites from "@/views/FavoritesView.vue";
import Checkout from "@/views/CheckOut.vue";
import Reviews from "@/views/ReviewsView.vue";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "/home",
    name: "Home",
    component: Home
  },
  {
    path: "/cart",
    name: "Cart",
    component: Cart,
    meta: { requiresAuth: true }
  },
  {
    path: "/book-detail",
    name: "BookDetail",
    component: BookDetail,
    props: true
  },
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "/register",
    name: "Register",
    component: Register
  },
  {
    path: "/orders",
    name: "Orders",
    component: Orders,
    meta: { requiresAuth: true }
  },
  {
    path: "/favorites",
    name: "Favorites",
    component: Favorites,
    meta: { requiresAuth: true }
  },
  {
    path: "/checkout",
    name: "Checkout",
    component: Checkout,
    meta: { requiresAuth: true }
  },
  {
    path: "/reviews",
    name: "Reviews",
    component: Reviews,
    meta: { requiresAuth: true }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.getters.isLoggedIn) {
      next({
        path: "/login",
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;